"""
CPEM Boot-strapper (lib/bootstrapper.py)  
Copyright 2010, C.J. Steele, all rights reserved.

C.J. Steele <coreyjsteele@gmail.com>

The boot-strapper is responsible for establishing a certificate-
authenticated session to a database (remote or local), to grab 
configuration registers before initializing the main process.

The registers retrieved are stored in a memory-only Registry, 
but are saved on an as-needed/periodic basis to the remote server.
If the save to the remote server fails, the database is written to a 
local database and efforts are made periodically to synchronize with 
the database server.

The off-line database is stored in a file called cpemodb.db, and should 
be operable with sqlite3 tools.
"""
import os,sys,sqlite3,platform
sys.path.append('lib','..lib')
from Registry import *
from SecureXMLRPCClient import *


def getHostname():
    """getHostname()
    returns the 'short' or host name of the local machine.
    """
    hostname = platform.node().partition('.')[0].lower()
    if hostname is not None:
        return hostname
    return False
    '''end getHostname()'''


def getClientUID():
    """getClientUID()
    Checks to see if the client already has a local UID file, if not it generates
    one and saves it to disk.
    
    ClientUID is a string that consists of "HOSTNAME-RANDOMFINGERPRINT"
    """
    #TODO: check if the file exists, if it does then read and return the name.
    pass

def setClientUID():
    pass


def bootstrap(dbServer,dbPort,keyFile):
    """bootstrap()
    The bootstrap routine is responsible for both recovering from a crash, or 
    pre-populating the configuration registers from a remote(or local) server 
    at bootup, using RSA key pairs to authenticate.
    """
    if offlineDatabaseExists() is True:
        # open the local ODB, because there was one.
        try:
            bootstrapReg = SQLRegistry("file://%x" % (odbFileName()))
            sanityCheck = bootstrapReg.get('root.sanityCheck')
            if int(sanityCheck) is 1:
                #TODO: get the bits and pieces
                return bootstrapReg
            else:
                return(-1)
        except(SQLRegistryError,errstr):
            print('E: we could not connect to the off-line database.  Please contact technical support. ("%s")' % (connErr[0]))
            return False
    else:
        #TODO: there was no off-line database, so go out and get the relevant 
        # registry bits using SecureXMLRPC
        odbFN = odbFileName()
        try:
            client = SecureXMLRPCClient(dbServer,dbPort,keyFile)
            for(regkey,regval) in client.getScope('client.globalcfg.'):
                pass
            if client is True:
                #NOTE: we've got a valid connection to the RPC server!
                pass
            else:
                # TODO: handle this better? 
                print('E: could not connect to local database or remote!  Shutting down.')
                return False
        except:
            pass
'''end bootstrap()'''

def syncODB(remoteRegistry,localFile=odbFileName()):
    pass


def odbFileName(path='%s' % (os.getcwd()),file="cpemodb.db"):
    """odbFileName( path, file )
    returns a 'properly' formatted string containing the 'anticipated' name of the off-line database.
    
    os.getcwd() will return a "properly" formatted current working directory, so the use of os.sep rounds it out.
    """
    return '%s%s%s' % (path,os.sep,file)
'''end odbFileName()'''


def offlineDatabaseExists(odbfile=odbFilename()):
    """offlineDatabaseExists( odbfile )
    boolean function to check for the existance of an off-line database 
    file.  if the file is present, it returns True, otherwise, False.
    """
    try:
        fileHandle = open(odbfile,'r')
        return fileHandle
    except IOError:
        return False
'''end offlineDatabaseExists()'''
